
package com.phevos.web.cas.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public final  class SecureURL
{

    private static final Logger logger = LoggerFactory.getLogger(SecureURL.class.getName());
    /**
     * For testing only...
     */
    public static void main(String args[]) throws IOException
    {
        System.setProperty("java.protocol.handler.pkgs", "com.sun.net.ssl.internal.www.protocol");
        System.out.println(SecureURL.retrieve(args[0]));
    }

    /**
     * Retrieve the contents from the given URL as a String, assuming the URL's server matches what we expect it to match.
     */
    public static String retrieve(String url) throws IOException
    {
        BufferedReader r = null;
        try
        {
            URL u = new URL(url);
            if (!u.getProtocol().equals("http"))
                throw new IOException("only 'http' URLs are valid for this method");
            URLConnection uc = u.openConnection();
            uc.setRequestProperty("Connection", "close");
            java.io.InputStream is = uc.getInputStream();
            r = new BufferedReader(new InputStreamReader(is));
            String line;
            StringBuffer buf = new StringBuffer();
            while ((line = r.readLine()) != null)
                buf.append(line + "\n");
            return buf.toString();
        }
        catch (IOException e)
        {
            logger.error("",e);
            throw e;
        }
        finally
        {
            try
            {
                if (r != null)
                    r.close();
            }
            catch (IOException ex)
            {
                logger.error("",ex);
            }
        }
    }
}
